/**
 * @NApiVersion 2.x
 * @NScriptType MapReduceScript
 */
define(['N/search', 'N/record', "N/http"], function (search, record, http) {

    function getInputData() {
        return search.create({
            type: 'customrecord_fba_inbound_shipment',
            columns: ['custrecord_inbound_shipmentid',
                'custrecord_inbound_store.custrecord_store_seller_id',
                'custrecord_inbound_store',
                'custrecord_inbound_tolocation',
                'custrecord_inbound_vendor'],
            filters: [['custrecord_inbound_po', 'is', '@NONE@']]
        }).run().getRange(0, 30);
    }

    function map(context) {
        var recId = JSON.parse(context.value).id;
        var result = JSON.parse(context.value).values;
        var sellerId = result['custrecord_inbound_store.custrecord_store_seller_id'];
        var shipmentId = result['custrecord_inbound_shipmentid'];
        var toLocationId = result['custrecord_inbound_tolocation'][0].value;
        var vendorId = result['custrecord_inbound_vendor'][0].value;
        var storeId = result['custrecord_inbound_store'][0].value;
        var requestBody = {
            "sellerId": sellerId,
            "shipmentId": shipmentId,
            "nextToken": ""
        };
        var members;
        try { //try name : update ids
            /* do {
                 try {//try name : post o2o
                     var response = http.post({
                         url: "http://112.74.55.237:8001/inbound/listInboundShipmentItems",
                         headers: {
                             "Content-Type": "application/json",
                             "Accept": "*!/!*"
                         },
                         body: JSON.stringify(requestBody)
                     });
                     log.debug({title: 'requestBody', details: JSON.stringify(requestBody)});
                     log.debug({title: 'response', details: JSON.stringify(response)});
                     if (response.code == 200) {
                         var responseBody = JSON.parse(response.body);
                         if (requestBody.nextToken != "") {
                             members = responseBody.ListInboundShipmentItemsByNextTokenResult.ItemData.Member;
                         } else {
                             members = responseBody.ListInboundShipmentItemsResult.ItemData.Member;
                         }
                         var nextToken;
                         if (requestBody.nextToken != "") {
                             nextToken = responseBody.ListInboundShipmentItemsByNextTokenResult.NextToken;
                         } else {
                             nextToken = responseBody.ListInboundShipmentItemsResult.NextToken;
                         }
                         if (nextToken) {
                             requestBody.nextToken = nextToken;
                         } else {
                             requestBody.nextToken = "";
                             break;
                         }
                     } else {
                         requestBody.nextToken = "";
                         throw response.body;
                     }
                 } catch (e) {
                     requestBody.nextToken = "";
                     log.debug({title: "error", details: JSON.stringify(e)});
                     throw JSON.stringify(e);
                 }
             } while (requestBody.nextToken != "");*/
            try {
                //var itemData = {};
                // for (var j = 0; j < members.length; j++) {
                //     var itemId;
                //     try {
                //          itemId = getItemIdBySellerSkuAndStoreId(members[j].SellerSKU, storeId);
                //     } catch (e) {
                //         continue;
                //     }
                //     if (itemData[itemId]) {
                //         itemData[itemId] += members[j].QuantityShipped;
                //     } else {
                //         itemData[itemId] = members[j].QuantityShipped;
                //     }
                // }
                var itemData = {
                    "25": 3
                }
                log.debug('itemData', itemData);
                var po = record.create({type: 'purchaseorder', isDynamic: true});
                po.setValue('entity', vendorId);
                po.setValue('location', toLocationId);
                for (var itemid in itemData) {
                    po.selectNewLine('item');
                    po.setCurrentSublistValue('item', 'item', itemid);
                    po.setCurrentSublistValue('item', 'quantity', itemData[itemid]);
                    po.commitLine('item');
                }
                var poId = po.save();
                record.submitFields({
                    type: 'customrecord_fba_inbound_shipment',
                    id: recId,
                    values: {custrecord_inbound_po: poId}
                });
                log.audit('po创建成功!id:', poId);
            } catch (e) {
                log.error('po创建失败', JSON.stringify(e));
                throw JSON.stringify(e);
            }
        } catch (e) {
            // record.submitFields({
            //     type: 'customrecord_fba_inbound_shipment',
            //     id: recId,
            //     values: {
            //         'custrecord_fba_shipment_msg': JSON.stringify(e),
            //         'custrecord_fba_shipment_id_status': 17
            //     }
            // });
        }

    }

    function reduce(context) {
    }

    function summarize(summary) {
    }

    function getItemIdBySellerSkuAndStoreId(sellerSku, storeId) {
        var itemId;
        search.create({
            type: 'kititem',
            columns: [],
            filters: [['custitem_platformsku', 'is', sellerSku],
                'and', ['custitem_platform_store_information', 'is', storeId]]
        }).run().each(function (result) {
            itemId = result.id;
        });
        return itemId;
    }

    return {
        getInputData: getInputData,
        map: map,
        reduce: reduce,
        summarize: summarize
    };
});